/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aptech.edu.assigment.survey;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import nu.xom.Attribute;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Node;
import nu.xom.Nodes;
import nu.xom.Serializer;
import nux.xom.xquery.XQueryUtil;

/**
 *
 * @author thanhtq
 */
public class SurveyDao {

    public static final String SURVEY_XML = "D:\\Survey\\Survey.xml";
    public static final String SURVEY_XPATH = "//Survey/categorys/category";
    private Document doc = null;

    public Document create(Survey survey) {
        try {
            Builder builder = new Builder();
            doc = builder.build(new File(SURVEY_XML));
            Node nodes = doc.query(SURVEY_XPATH).get(0);
            Element content = new Element("content");
            content.appendChild(survey.getContentSurvey());
            Element question = new Element("questions");
            question.appendChild(" ");
            Element answer = new Element("answers");
            answer.appendChild(" ");
            Element comment = new Element("comment");
            comment.appendChild(" ");
            comment.appendChild(survey.getCommenSurvey());
            Element category = new Element("category");
            Attribute id = new Attribute("id", survey.getIdSurvey());
            category.addAttribute(id);
            category.appendChild(content);
            category.appendChild(question);
            category.appendChild(answer);
            category.appendChild(comment);
            nodes.getParent().fastInsertChild(category, nodes.getParent().getChildCount());
            save();
            return doc;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public void updateAnswer(Answer answer, String idSurvey) {
        try {
            Builder builder = new Builder();
            doc = builder.build(new File(SURVEY_XML));
            System.out.println(doc.toXML());
            System.out.println(idSurvey);
            Node n = doc.query("//Survey/categorys/category[@id='" + idSurvey + "']").get(0);
            Node nodes = n.query("answers/text()").get(0);
            Element option = new Element("option");
            option.appendChild(answer.getOption());
            Element QuesID = new Element("QuesID");
            QuesID.appendChild(answer.getQuesId());
            Element rate = new Element("rate");
            rate.appendChild("0");
            Element answerElement = new Element("answer");
            Attribute id = new Attribute("id", answer.getId());
            answerElement.addAttribute(id);
            answerElement.appendChild(option);
            answerElement.appendChild(QuesID);
            answerElement.appendChild(rate);
            nodes.getParent().fastInsertChild(answerElement, nodes.getParent().getChildCount());
            save();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public Document updateQuestion(Question question, String idSurvey) {
        try {
            Builder builder = new Builder();
            doc = builder.build(new File(SURVEY_XML));
            Node n = doc.query("//Survey/categorys/category[@id='" + idSurvey + "']").get(0);
            Node nodes = n.query("questions/text()").get(0);
            Element content = new Element("Content");
            content.appendChild(question.getContent());
            Element questionElement = new Element("question");
            Attribute id = new Attribute("id", question.getId());
            questionElement.addAttribute(id);
            questionElement.appendChild(content);
            nodes.getParent().fastInsertChild(questionElement, nodes.getParent().getChildCount());
            save();
            return doc;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static void main(String argm[]) {

//        Random random = new Random();
//        int numRandom = random.nextInt();
//        String idSurvey = String.valueOf(numRandom);
//        Survey s = new Survey();
//        s.setName("thanhtq");
//        s.setCommenSurvey("");
//        s.setContentSurvey("Survey 1");
//        s.setIdSurvey(String.valueOf(idSurvey));
//        //new SurveyDao().create(s);
//
//        numRandom = random.nextInt();
//        String idQuestion = String.valueOf(numRandom);
//        Question q = new Question();
//        q.setContent("question 5");
//        q.setId(idQuestion);
//        new SurveyDao().updateQuestion(q,"1370505123");//id of Survey
//
//        numRandom = random.nextInt();
//        String idAnswer = String.valueOf(numRandom);
//        Answer a = new Answer();
//        a.setId(idAnswer);
//        a.setOption("option 1");
//        a.setQuesId(idQuestion);//Id of Question
//        a.setRate("0");
//        new SurveyDao().updateAnswer(a,"1370505123");//id of Survey

        new SurveyDao().readSurvey("1");
    }

    public void update(int rate, String surveyId,String answerId) {

        try {
            Builder builder = new Builder();
            doc = builder.build(new File(SURVEY_XML));
            XQueryUtil.update(doc, "//Survey/categorys/category[@id='"+surveyId+"']/answers/answer[@id='"+answerId+"']/rate", String.valueOf(rate));
            save();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void removeSurvey(String id) {
        try {
            Builder builder = new Builder();
            doc = builder.build(new File(SURVEY_XML));
            Node node = doc.query(SURVEY_XPATH).get(0);
            Node nodeChild = doc.query("//Survey/categorys/category[@id='" + id + "']").get(0);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public boolean save() {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(SURVEY_XML));
            Serializer ser = new Serializer(fos);
            ser.write(doc);
            ser.flush();
            return true;
        } catch (Exception ex) {
            return false;
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
            }
        }
    }

    public Survey readSurvey(String id) {
        Survey survey = new Survey();
        try {
            doc = new Builder().build(new File(SURVEY_XML));

            Node node = doc.query("//Survey/categorys/category[@id='" + id + "']").get(0);
            survey.setIdSurvey(node.query("@id").get(0).getValue());
            survey.setContentSurvey(node.query("content").get(0).getValue());
            survey.setCommenSurvey(node.query("comment").get(0).getValue());
            survey.setQuestion(readQuestion(id));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return survey;
    }

    public List<Survey> read() {

        List<Survey> surveys = new ArrayList<Survey>();
        List<String> questId = new ArrayList<String>();
        Survey survey;
        try {
            Document doc = new Builder().build(new File(SURVEY_XML));
            Nodes nodes = XQueryUtil.xquery(doc, "//Survey/categorys/category");
            for (int i = 0; i < nodes.size(); i++) {
                survey = new Survey();
                survey.setIdSurvey(nodes.get(i).query("@id").get(0).getValue());
                survey.setContentSurvey(nodes.get(i).query("content").get(0).getValue());
                survey.setCommenSurvey(nodes.get(i).query("comment").get(0).getValue());
                Nodes questions = nodes.get(i).query("questionId/id[@enable='1']");
                for (int j = 0; j < questions.size(); j++) {
                    questId.add(questions.get(j).query("@id").get(0).getValue());
                }
                survey.setQuestionId(questId);
                surveys.add(survey);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return surveys;
    }

    public List<Question> readQuestion(String id) {
        List<Question> questions = new ArrayList<Question>();
        Question question;
        try {
            doc = new Builder().build(new File(SURVEY_XML));
            Node node = doc.query("//Survey/categorys/category[@id='" + id + "']").get(0);
            Nodes nodes = node.query("questions/question");
            for (int i = 0; i < nodes.size(); i++) {
                question = new Question();
                question.setId(nodes.get(i).query("@id").get(0).getValue());
                question.setContent(nodes.get(i).query("Content").get(0).getValue());
                question.setListAnswer(readAnswer(id, question.getId()));
                questions.add(question);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return questions;
    }

    public List<Answer> readAnswer(String id, String quesId) {
        List<Answer> answers = new ArrayList<Answer>();
        //numberManTl = 0;
        Answer answer;
        try {
            doc = new Builder().build(new File(SURVEY_XML));
            Node node = doc.query("//Survey/categorys/category[@id='" + id + "']").get(0);
            Nodes nodes = node.query("answers/answer");
            for (int i = 0; i < nodes.size(); i++) {
                answer = new Answer();
                if (nodes.get(i).query("QuesID").get(0).getValue().equals(quesId)) {
                    answer.setId(nodes.get(i).query("@id").get(0).getValue());
                    answer.setOption(nodes.get(i).query("option").get(0).getValue());
                    answer.setQuesId(nodes.get(i).query("QuesID").get(0).getValue());
                    answer.setRate(nodes.get(i).query("rate").get(0).getValue());
                    //numberManTl += Integer.parseInt(answer.getRate());
                    answers.add(answer);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return answers;
    }
}
